package com.aisi.backend.filter;

import cn.hutool.core.util.StrUtil;
import com.aisi.backend.domain.RestBean;
import com.aisi.backend.domain.RestCode;
import com.aisi.backend.utils.Const;
import com.aisi.backend.utils.JwtUtils;
import com.aisi.backend.utils.WebUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @Author: shenjianZ
 * @Date: 2024/4/30 下午10:50
 * @Description:
 */


@WebFilter({"/api/index/**","/api/user/info","/api/user/details","/api/user/saveDetails","/api/forum/*","/api/image/uploadImage"})
public class LoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        String token = req.getHeader("authorization");
        token = token.replace("Bearer ", "");
        req.setAttribute("userId",JwtUtils.getJWTUserId(token));
        if (StrUtil.isBlank(token)) {
            WebUtils.writeJson(res, RestBean.failure(RestCode.TOKEN_EMPTY));
            return;
        }
        String verifyToken = JwtUtils.resolveJwtToken(token);
        if (Const.TOKEN_INVALID.equals(verifyToken)) {
            WebUtils.writeJson(res, RestBean.failure(RestCode.TOKEN_INVALID));
        } else if (Const.TOKEN_EXPIRE.equals(verifyToken)) {
            WebUtils.writeJson(res, RestBean.failure(RestCode.TOKEN_EXPIRE));
        } else {
            filterChain.doFilter(req, res);
        }
    }
}